package suzf.top.usercenter.ui.activity

import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_regiser.*
import org.jetbrains.anko.toast
import suzf.top.base.common.AppManager
import suzf.top.base.ext.enable
import suzf.top.base.ext.onClick
import suzf.top.base.ui.activity.BaseMvpActivity
import suzf.top.usercenter.R
import suzf.top.usercenter.injection.component.DaggerUserComponent
import suzf.top.usercenter.injection.module.UserModule
import suzf.top.usercenter.presenter.RegisterPresenter
import suzf.top.usercenter.presenter.view.RegisterView

/**
 *  注册界面
 *========================
 * Created with AndroidStudio
 * Author:Mr.Su
 * Date:2019-09-07
 * Time:20:46
 * ========================
 */
class RegisterActivity : BaseMvpActivity<RegisterPresenter>(), RegisterView, View.OnClickListener {

    private var pressTime: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_regiser)

        //initView()
    }

    /**
     * 初始化视图
     */
    private fun initView() {

        mRegisterBtn.enable(mMobileEt, { isBtnEnable() })
        mRegisterBtn.enable(mVerifyCodeEt, { isBtnEnable() })
        mRegisterBtn.enable(mPwdEt, { isBtnEnable() })
        mRegisterBtn.enable(mPwdConfirmEt, { isBtnEnable() })

        mVerifyCodeBtn.onClick(this)
        mRegisterBtn.onClick(this)
    }

    /**
     * Dagger注入
     */
    override fun injectComponent() {
        DaggerUserComponent.builder()
                .activityComponent(activityComponent)
                .userModule(UserModule())
                .build()
                .inject(this)
        mPresenter.mView = this
    }

    /**
     * 注册回调
     */
    override fun onRegisterResult(result: String) {
        toast(result)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.mVerifyCodeBtn -> {
                mVerifyCodeBtn.requestSendVerifyNumber()
                toast("验证码已发送")
            }
            R.id.mRegisterBtn -> {
                mPresenter.register(mMobileEt.text.toString(), mPwdEt.text.toString(), mVerifyCodeEt.text.toString())
            }
        }
    }

    /**
     * 重写返回键
     */
    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if (time - pressTime > 2000) {
            toast("再按一次退出程序")
            pressTime = time
        } else {
            AppManager.instance.exitApp(this)
        }
    }

    /**
     * 判断按钮是否可用
     */
    private fun isBtnEnable(): Boolean {
        return mMobileEt.text.isNullOrEmpty().not() and
                mVerifyCodeEt.text.isNullOrEmpty().not() and
                mPwdEt.text.isNullOrEmpty().not() and
                mPwdConfirmEt.text.isNullOrEmpty().not()
    }
}
